package com.example.demo.controller.admin;

import com.example.demo.common.CommonResult;
import com.example.demo.common.StatusCode;
import com.example.demo.domain.Comment;
import com.example.demo.domain.User;
import com.example.demo.dto.ReturnCommentDTO;
import com.example.demo.dto.ReturnUserDTO;
import com.example.demo.service.CommentService;
import com.example.demo.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liuchao
 * @version 1.0
 * @date 2024/11/5
 */
@RestController("adminCommentController")
@RequestMapping("/admin")
public class CommentController {

    @Resource
    private CommentService commentService;
    @Resource
    private UserService userService;

    @GetMapping("/listComment")
    public CommonResult<List<ReturnCommentDTO>> listComment() {
       CommonResult<List<ReturnCommentDTO>> commonResult = new CommonResult<>();
        List<ReturnCommentDTO> returnCommentList = new ArrayList<>();

        // 获取所有的评论
        List<Comment> commentList = commentService.list();

        // 遍历所有的评论
        for (Comment comment : commentList) {
            // 创建一个返回评论对象
            ReturnCommentDTO commentDTO = new ReturnCommentDTO();
            // 获取当前评论的用户信息
            User user = userService.getById(comment.getUserId());
            // 创建一个返回用户对象
            ReturnUserDTO returnUserDTO = new ReturnUserDTO();
            // 将用户信息复制到返回用户对象中
            BeanUtils.copyProperties(user, returnUserDTO);

            // 将当前评论和用户信息复制到返回评论对象中
            commentDTO.setComment(comment);
            commentDTO.setUser(returnUserDTO);

            // 将当前返回评论对象添加到返回评论列表中
            returnCommentList.add(commentDTO);
        }

        // 返回成功状态码和消息
        commonResult.setCode(StatusCode.COMMON_SUCCESS.getCode());
        commonResult.setMessage(StatusCode.COMMON_SUCCESS.getMessage());
        // 将返回评论列表设置到返回结果中
        commonResult.setData(returnCommentList);

        return commonResult;
    }
}
